import axios from 'axios';
import { Message, Loading } from 'element-ui';
import Store from "@/store";
import router from "@/router";
import Storage from "@/store/storage";
// 创建axios实例
const Http = axios.create({
    // 请求基地址
    baseURL: process.env.VUE_APP_BASE_URL_PROXY,
    // 超时设置
    timeout: 5000,
    headers:{
        'Content-Type':'application/json;charset=utf-8'
    }
})

let loading;
//正在请求的数量
let requestCount = 0
//显示loading
const showLoading = () => {
    if (requestCount === 0 && !loading) {
        //加载中显示样式可以自行修改
        loading = Loading.service({
            text: "loading......",
            background: 'rgba(0, 0, 0, 0.7)',
            spinner: 'el-icon-loading',
        })
    }
    requestCount++;
}
// 隐藏loading
const hideLoading = () => {
    requestCount--
    if (requestCount === 0) {
        loading.close()
    }
}

Http.interceptors.request.use(
    (config) => {
        console.log("TOKEN")
        showLoading()
        // 添加token
        console.log( Store.state.token.admin.tokenValue)
        config.headers[Store.state.token.tokenName] = Store.getters.getTokenValue
        config.headers[Store.state.token.admin.tokenHead] = Store.getters.getAdminTokenValue
        return config
    }
)

// 响应拦截器
Http.interceptors.response.use(
    (res) => {
        hideLoading()
        // 存token
        if (res.headers[Store.state.token.tokenName]){
            Store.commit("setTokenValue", res.headers[Store.state.token.tokenName]);
        }
        // 存token
        if (res.headers[Store.state.token.admin.tokenHead]){
            Store.commit("setAdminTokenValue", res.headers[Store.state.token.admin.tokenHead]);
        }
        return Promise.resolve(res.data)
    },
    (error) => {
        console.log('err' + error)
        hideLoading()
        let { message } = error.response.data;
        switch (error.response.status) {
            case 301:
                Store.commit("delTokenValue")
                Message.error({
                    message: message,
                    duration: 4 * 1000
                });
                router.replace({
                    path: '/hotel/room'
                })
                return Promise.resolve(error.response.data)
            case 302:
                Store.commit("delAdminTokenValue")
                Message.error({
                    message: message,
                    duration: 4 * 1000
                });
                router.replace({
                    path: '/admin'
                })
                return Promise.resolve(error.response.data)

        }
        Message.error({
            message: message,
            duration: 5 * 1000
        })
        return Promise.reject(error)
    }
)

export default Http;